﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace SlamCms.SharePoint.Migration
{
	public class MigratableSiteCollection : IMigratable
	{
		public List<MigratableSite> Sites { get; set; }

		public string Url { get; set; }

		public MigratableSiteCollection()
		{
			this.Sites = new List<MigratableSite>();
		}

		#region Methods

		public MigratableList GetList(string id)
		{
			MigratableList list = null;
			Sites.ForEach(s =>
				{
					if (list == null) list = s.Lists.Where(l => l.Id.Equals(id)).FirstOrDefault();
				});
			return list;
		}

		public MigratableSite GetSite(string url)
		{
			return this.Sites.Where(o => o.Url.Equals(url)).FirstOrDefault();
		}

		#endregion

		#region Serialization

		public XElement ToXml()
		{
			XElement node = new XElement("SiteCollection");
			node.Add(new XAttribute("Url", Url));
			node.Add(SitesToXml());
			return node;
		}

		public void FromXml(XElement node)
		{
			this.Url = node.Attribute("Url").Value;
			SitesFromXml(node);
		}

		private XElement SitesToXml()
		{
			XElement node = new XElement("Sites");
			foreach (MigratableSite site in Sites)
			{
				node.Add(site.ToXml());
			}
			return node;
		}

		private void SitesFromXml(XElement node)
		{
			var sitesNode = node.Element("Sites");
			if (sitesNode.HasElements)
			{
				foreach (XElement child in sitesNode.Elements())
				{
					MigratableSite site = new MigratableSite();
					site.FromXml(child);
					this.Sites.Add(site);
				}
			}
		}

		#endregion
	}
}
